package com.tuyan.aixiang.api.helper;


import com.google.gson.FieldNamingPolicy;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tuyan.aixiang.common.Constant;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiManager {

    private static ApiManager instance;

//    private static Retrofit retrofit;

    private Map<String, Retrofit> retrofitMap = new HashMap<>();

    private ApiManager() {
    }


    public static ApiManager getInstance() {

        if (null == instance) {
            synchronized (ApiManager.class) {
                if (null == instance) {
                    instance = new ApiManager();
                }
            }
        }
        return instance;
    }

    public void init(String baseUrl) {
        //set logger
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new NetLog());
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new HeaderInterceptor())
                .retryOnConnectionFailure(true)//默认重试一次，若需要重试N次，则要实现拦截器。
//                .addNetworkInterceptor(loggingInterceptor)
                .addInterceptor(loggingInterceptor)
//                .addNetworkInterceptor(loggingInterceptorHeader)
//                    .retryOnConnectionFailure(true)
                .connectTimeout(Constant.HTTP_TIMEOUT, TimeUnit.SECONDS)
                .build();

        Gson gson = new GsonBuilder()
                .setLenient()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) // 下划线
                .create();

        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
//                .addConverterFactory(ResponseConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        retrofitMap.put(baseUrl, retrofit);
    }

    public Retrofit getRetrofit(String baseUrl, String service) {
        String base = baseUrl + service;
        if(null == retrofitMap.get(base)){
            init(base);
        }
        return retrofitMap.get(base);
    }

}